package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKE_KEY;
import static com.hmdp.utils.RedisConstants.FEED_PREFIX;
import static com.hmdp.utils.SystemConstants.DEFAULT_FEED_PAGE_SIZE;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate strRedisTemplate;
    @Resource
    private IFollowService followService;

    @Override
    public Result queryBlogWithId(String id) {
        // 1、查询博客
        Blog blog = query().eq("id", id).one();
        if (blog == null) {
            return Result.fail("id为" + id + "的博客不存在");
        }
        // 当前用户是否点赞指定博客
        isLikedBolg(blog);
        // 查询博客的用户信息
        queryBlogUser(blog);
        // 3、封装返回结果

        log.info("查询结果信息：{}", blog);
        return Result.ok(blog);
    }


    /**
     * 当前用户是否点赞指定博客
     *
     * @param blog
     */
    private void isLikedBolg(Blog blog) {
        String blogKey = "blog:liked:" + blog.getId().toString();
        UserDTO user = UserHolder.getUser();
        // 用户上下文不存在
        if (user == null) {
            return;
        }
        Double score = strRedisTemplate.opsForZSet().score(blogKey, user.getId().toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result likeBlog(Long id) {
        // 用户上下文
        UserDTO currentUser = UserHolder.getUser();
        // 1、查询博客
        Blog blog = query().eq("id", id).one();
        // 2、查询结果校验
        if (blog == null) {
            return Result.fail("id为" + id + "的博客不存在");
        }
        // 3、存在，查询当前用户是否已经点赞（redis）
        // key为博客的id
        String key = "blog:liked:" + id;
//        Boolean isLiked = strRedisTemplate.opsForSet().isMember(key, currentUser.getId().toString());
        Double score = strRedisTemplate.opsForZSet().score(key, currentUser.getId().toString());
        // 3.1、未点赞
        if (score == null) {
            // 3.1.1、点赞
            strRedisTemplate.opsForZSet().add(key, currentUser.getId().toString(), System.currentTimeMillis());
            // 3.1.2、更新点赞数
            this.update()
                    .setSql("liked = liked + 1").eq("id", id).update();
        } else {
            // 3.2、已点赞，取消点赞
            strRedisTemplate.opsForZSet().remove(key, currentUser.getId().toString());
            // 3.2.2、更新点赞数
            this.update()
                    .setSql("liked = liked - 1").eq("id", id).update();
        }
        // 4、返回结果
        return Result.ok(blog);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            // 查询blog有关的用户信息
            queryBlogUser(blog);
            // 当前用户是否点赞指定博客
            isLikedBolg(blog);
        });
        return Result.ok(records);
    }

    /**
     * 查询博客的用户信息
     *
     * @param blog
     */
    public void queryBlogUser(Blog blog) {
        // 2、查询用户信息
        User user = userService.query().eq("id", blog.getUserId()).one();
        if (user == null) {
            log.info("id为" + blog.getUserId() + "的用户不存在");
            return;
        }
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result getBlogLikes(String id) {
        String key = BLOG_LIKE_KEY + id;
        // 查询博客
        Blog blog = query().eq("id", id).one();
        if (blog == null) {
            return Result.fail("id为" + id + "的博客不存在");
        }
        // 获取点赞用户信息 top5
        List<Long> userIds = strRedisTemplate.opsForZSet().range(key, 0, 4)
                .stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        String joinStr = StrUtil.join(",", userIds);
        if (userIds == null || userIds.isEmpty()) {
            return Result.fail("暂无点赞用户");
        }
        // 查询用户信息
        List<User> users = userService.query().in("id", userIds).last("ORDER BY FIELD(id, " + joinStr + ")").list();
        // 封装结果
        return Result.ok(users);
    }

    @Override
    public Result queryBlogOfUser(Integer current, String userId) {
        // 查询用户id是否存在
        User user = userService.query().eq("id", userId).one();
        if (user == null) {
            return Result.fail("用户id为" + userId + "的用户不存在");
        }
        Page<Blog> pageQuery = new Page<Blog>().setCurrent(current).setSize(SystemConstants.MAX_PAGE_SIZE);
        List<Blog> blogs = this.query().eq("user_id", userId).page(pageQuery).getRecords();
        return Result.ok(blogs);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null || user.getId() == null) {
            return Result.fail("用户未登录");
        }
        blog.setUserId(user.getId());
        // 保存探店博文
        save(blog);
        // 推送博客到粉丝收件箱
        new QueryWrapper<Follow>().eq("follow_user_id", user.getId());
        List<Follow> fens = followService.query().eq("follow_user_id", user.getId()).list();
        if (fens == null || fens.isEmpty()) {
            log.info("当前用户没有粉丝，不推送");
            return Result.ok(blog);
        }
        fens.forEach(fee -> {
            Long userId = fee.getUserId(); // 粉丝id
            String key = FEED_PREFIX + userId.toString(); // 粉丝feed缓存key
            strRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        });
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 1.获取收件箱 ZREVRANGEBYSCORE z1 4 0 WITHSCORES LIMIT 1 3
        // 注：第一次查询offset为0，后续查询1（不包含上一次的最小值）
        String key = FEED_PREFIX + userId.toString();
        Set<ZSetOperations.TypedTuple<String>> typedTuples = strRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, DEFAULT_FEED_PAGE_SIZE);
        // 校验
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 解析数据 blogId、minTime（时间戳）、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        AtomicLong minTime = new AtomicLong();
        typedTuples.forEach(tuple -> {
            Long blogId = Long.parseLong(tuple.getValue());
            minTime.set(tuple.getScore().longValue());
            ids.add(blogId);
        });
        // 2.查询博客信息(注意查询数据的顺序性)
        String joinStr = StrUtil.join(",", ids);
        List<Blog> blogs = this.query().in("id", ids).last("ORDER BY FIELD(id, " + joinStr + ")").list();
        blogs.forEach(blog -> {
            // 查询用户信息
            queryBlogUser(blog);
            // 当前用户是否点赞指定博客
            isLikedBolg(blog);
        });
        // 3.查询用户信息
        // 封装数据，并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime.get());
        scrollResult.setOffset(1); // 后续查询，偏移量均为1
        return Result.ok(scrollResult);
    }
}
